﻿using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using zijian666.SuperConvert.Interface;

namespace zijian666.SuperConvert.Json
{
    internal class PackagingObjectJsonConverert : JsonConverterFactory
    {

        public override bool CanConvert(Type type)
            => typeof(IObjectReference).IsAssignableFrom(type);

        public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options)
        {
            return (JsonConverter)Activator.CreateInstance(typeof(InnerConverter<>).MakeGenericType(typeToConvert));
        }

        class InnerConverter<T> : JsonConverter<T>
            where T : IPackagingObject
        {
            public override bool CanConvert(Type type) => true;

            public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options)
            {

                var obj = value.GetObject();
                if (ReferenceEquals(obj, value))
                {
                    JsonSerializer.Serialize(writer, obj);
                }
                else
                {
                    JsonSerializer.Serialize(writer, obj, options);
                }
            }

            public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
            {
                throw new NotImplementedException();
            }
        }

    }
}
